<?php

use Nette\Application\UI\Form,
	Nette\Environment,
	Nette\Utils;

use Grido\Grid,
	Grido\Components\Columns\Column,
	Grido\Components\Columns\Date,
	Grido\Components\Filters\Filter;

/**
 * Places presenter.
 */
class PlacesPresenter extends BasePresenter
{
	/**
	 * render Default
	 *
	 */
	public function renderDefault()
	{
		//$places = $this->context->places->getAll();

		//$this->template->places = $places;
	}

	protected function createComponentGrid($name)
	{
	    $grid = new Grid($this, $name);

	    $grid->setModel($this->context->places->getAll());
	    $grid->setDefaultSort(array('created' => Column::DESC));

	   	$grid->addColumn('created', 'Vytvořeno', Column::TYPE_DATE)->setSortable()
		   	 ->setDateFormat(Date::FORMAT_DATE);
        $grid->addColumn('nameUser', 'Autor')->setSortable();
        $grid->addColumn('name', 'Název')->setSortable();
        $grid->addColumn('city', 'Město')->setSortable();
        $grid->addColumn('street', 'Ulice')->setSortable();
        $grid->addColumn('coord', 'GPS')->setSortable();
		$grid->addAction('detail', 'Detail')->setIcon('list-alt');
		$grid->addAction('edit', 'Edit')->setIcon('pencil');
		$grid->addAction('delete', 'Delete')->setIcon('trash');
	}

	/**
	 * render Detail
	 *
	 * @param  int $id
	 */
	public function renderDetail($id)
	{
		$place = $this->context->places->get($id);

		$this->template->place = $place;
	}

	/**
	 * render Edit
	 *
	 * @param  int $id
	 */
	public function renderEdit($id)
	{
		$place = $this->context->places->get($id);

		$this->getComponent('addForm')->setValues($place);

		$this->template->place = $place;
	}

	/**
	 * render Delete
	 *
	 * @param  int $id
	 */
	public function renderDelete($id)
	{
		$place = $this->context->places->get($id);

		$this->getComponent('deleteForm')->setDefaults($place);

		$this->template->place = $place;
	}

	/**
	 * Add Form control
	 *
	 * @return Nette\Application\UI\Form
	 */
	protected function createComponentAddForm()
	{
		return new Places\PlacesForm();
	}

	/**
	 * Delete Form control
	 *
	 * @return Nette\Application\UI\Form;
	 */
	protected function createComponentDeleteForm()
	{
		$form = new Form;
		$form->addHidden('id');
		$form->addSubmit('ok', 'Potvrdit');
		$form->addSubmit('storno', 'Storno');
		$form->onSuccess[] = $this->deleteFormAction;

		return $form;
	}

	/**
	 * delete Form Action
	 *
	 * @param  Form   $form [description]
	 */
	public function deleteFormAction(Form $form)
	{
		if($form['ok']->isSubmittedBy()) {
			$values = $form->getValues();

			$e = $this->context->places->delete($values);

			if($e instanceof DibiException) {
				$form->addError($e->getMessage());
				return;
			}

			$this->flashMessage('Místo bylo smazáno.');
		}

		$this->redirect('Places:');
	}

}